package ua.kharkov.khpi.tarasenko.bach.core.logging;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;


public class DailyLogRolloutJob implements Job {
	private static final Logger LOG = Logger
			.getLogger(DailyLogRolloutJob.class);

	private static final String FILE_NAME = "userActions.log";

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		Logger logger = Logger.getRootLogger(); // Defining the Logger

		FileAppender appender = (FileAppender) logger
				.getAppender("userActions");

		LOG.info("Daily roll out job executing!");

		File logsDir = new File(new File(appender.getFile()).getParent());
		File[] listOfFiles = logsDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				if (name.matches(FILE_NAME
						+ ". \\d{4}-\\d{2}-\\d{2}")) {
					return true;
				}
				return false;
			}
		});
		
		for (File file : listOfFiles) {
			try {
				LogRollOut.doRollOut(file);
			} catch (Exception e) {
				LOG.error("Failed to roll out log file \"" + file.getAbsolutePath() + "\" to database");
			}
		}
		
		deleteRolledFiles(listOfFiles);
		LOG.info("Logs are now rolled out to db.");
	}
	
	private void deleteRolledFiles(File[] listOfFiles) {
		for (File file : listOfFiles) {
			
			boolean isDeleted = file.delete();
			if (!isDeleted) {
				LOG.error("File \"" + file.getAbsolutePath() + "\" was not deleted!");
			}
		}
	}
}
